import { request } from 'utils/http'
import cloneDeep from 'lodash.clonedeep'

let globalConf = null
let personConf = null

export const getFlowStatus = (processInstanceId) => {
  const url = `${window.contextPath}/sys/emapflow/tasks/queryFlowState.do?processInstanceId=${processInstanceId}&responseType=JSON`
  return request(url)
}

const mergeGlobal = (opt, config) => {
  const realOpt = cloneDeep(config[opt.id])
  for (let i = 0; i < config._keepNames.length; i++) {
    const key = config._keepNames[i]
    if (opt[key] != null) {
        realOpt[key] = opt[key]
    }
  }
  
  return realOpt
}

export const fetchGlobalConf = () => {
  if (globalConf) {
    return Promise.resolve(globalConf)
  }

  const url = `${window.contextPath}/sys/eetablecore/options.json`
  return request(url).then(res => {
    globalConf = res
    return res
  })
}

export const getPersonInfo = () => {
  if (personConf) {
    return Promise.resolve(personConf)
  }
  const url = `${window.contextPath}/sys/${window.appNameEn}/public/help/notice.json`
  return request(url).then(res => {
    personConf = res
    return res
  })
}

export const fetchGrid = async (url, params) => {
  const globalConf = await fetchGlobalConf()
  const gridData = await showGridFn(url, params)
  // todo
  gridData.options = gridData.options.map(item => {
    return mergeGlobal(item, globalConf)
  })
  gridData.toolbar = gridData.toolbar.map(item => {
    return mergeGlobal(item, globalConf)
  })
  return {models: gridData}
}

export const showGridFn = (url, params) => {
  return request(url, {query: params}).then(res => {
    if(res.code === "0") {
      if(res.models) {
        let models = res.models
        return models
      }
    }
  })
}

export const getFlowTaskComment = (url, params) => {
  return request(url, {query: params}).then(res => {
      return res
  })
}
